var Textures;
var LevelSize;
var ImageSize;
var EnableControls;
var FreezePlayer;
var ElapsedTime; // UpdateTime in ms
var CarTimes; // SpawningTimes for lkws and cars
var CarRespawnTimes;
var RiverTimes; // Spawning Times for turtles and logs
var RiverRespawnTimes;
var AudioFrog;	// Standard audio file (played if the frog moves)
var AudioKillFrog;	// Audio file which is played if the frog gets killed
var AudioTraffic;	// Audio file which is played if frog is on a traffic field
var AudioWater;		// Audio file which is played if frog is on a water field
var CurrentGameMode;	// The game mode (USK12 or USK18)
var newGameMode;		
var StartTime;
var EndTime;
var Runtime;
var DriftFactor;
var BreakingLine;
var SpawnCars;
// ### ENUMERATIONS ###

var GameMode = 
{
	"USK18": 0,
	"USK12": 1	
};

var EntityType = 
{
	// lkw driving form right to the left
	"lkwleft": 0,
	"lkwright" : 1,
	"carleft": 2,
	"carright": 3,
	// turtles always swim against the river-floatingdirection
	// swim to left
	"turtle": 4,
	// swim to right
	"wood": 5
};

var FieldType =
{
	"grass": 0,
	"road": 1,
	"roadstripe": 2,
	"water": 3,
	"frog": 4,
	"jumpingFrog": 5,
	"deadFrog" : 6,
	"logleft": 7,
	"logmid": 8,
	"logright": 9,
	"turtle": 10,
	"lkwleft" : 11,
	"lkwmid" : 12,
	"lkwright" : 13,
	"carleft" : 14,
	"carmid" : 15,
	"carright" : 16,
	"phantomCol" : 17, // Invisble Field wich causes a collision and death of the frog
	"sinwater" : 18,
	"fly" : 19
};

var Direction =
{
	"up": 0,
	"down": 1,
	"left": 2,
	"right": 3,
	"none": 4
};

var KeyCode =
{
	"up": 38,
	"down": 40,
	"left": 37,
	"right": 39,
	"reset": 82
};
//### FUNCTIONS ###
function initGlobal() {
	// Load All textures
	loadTextures();
	// Set Vars
	DriftFactor = 0.02;
	LevelSize = new pointData(15, 20);
	ImageSize = new pointData(32, 32);
	ElapsedTime = 10;
	BreakingLine = new Array();
	SpawnCars = true;
	// Set Canvas Properties
	var canvas = document.getElementById("theCanvas");
	canvas.width = LevelSize.x * ImageSize.x;
	canvas.height = LevelSize.y * ImageSize.y;
	// center canvas
	canvas.style.position = "absolute";
	canvas.style.top = "50%";
	canvas.style.left = "50%";
	canvas.style.marginLeft = -canvas.width / 2 + "px";
	canvas.style.marginTop = -canvas.height / 2 + "px";
	// Load audio files
	AudioFrog = new Audio("");
	document.body.appendChild(AudioFrog);
	AudioFrog.src = '../audio/Frog.wav';	
	
	AudioKillFrog = new Audio("");
	document.body.appendChild(AudioKillFrog);
	AudioKillFrog.src = '../audio/Kill.wav';	
	
	AudioTraffic = new Audio("");
	document.body.appendChild(AudioTraffic);
	AudioTraffic.src = '../audio/Traffic.wav';	
	
	AudioWater = new Audio("");
	document.body.appendChild(AudioWater);
	AudioWater.src = '../audio/Water.wav';
	
	// Set default game mode
	CurrentGameMode	= GameMode.USK18;
	newGameMode = CurrentGameMode;
}

function loadTextures() {
	Textures = new Array();
	for(var i = 0; i < 100; i++)
		Textures.push(new Image());
	var colorPath = "";
	if(CurrentGameMode == GameMode.USK12)
	{
		colorPath = "clr/";
	}
	Textures[0].src = "../img/" + colorPath +  "g1.png";
	Textures[1].src = "../img/" + colorPath +  "g2.png";
	Textures[2].src = "../img/" + colorPath +  "g3.png";
	Textures[3].src = "../img/" + colorPath +  "w1.png";
	Textures[4].src = "../img/" + colorPath +  "w2.png";
	Textures[5].src = "../img/" + colorPath +  "w3.png";
	Textures[6].src = "../img/" + colorPath +  "frogger.png";
	Textures[7].src = "../img/" + colorPath +  "froggerJumping.png";
	Textures[8].src = "../img/" + colorPath +  "log1.png";
	Textures[9].src = "../img/" + colorPath +  "log2.png";
	Textures[10].src = "../img/" + colorPath +  "NA.png";
	Textures[11].src = "../img/" + colorPath +  "r1.png";
	Textures[12].src = "../img/" + colorPath +  "r2.png";
	Textures[13].src = "../img/" + colorPath +  "rs.png";
	Textures[14].src = "../img/" + colorPath +  "lkw1.png";
	Textures[15].src = "../img/" + colorPath +  "lkw2.png";
	Textures[16].src = "../img/" + colorPath +  "lkw3.png";
	Textures[17].src = "../img/" + colorPath +  "carleft.png";
	Textures[18].src = "../img/" + colorPath +  "carmid.png";
	Textures[19].src = "../img/" + colorPath +  "carright.png";
	Textures[20].src = "../img/" + colorPath + "turtle.png";
	Textures[21].src = "../img/" + colorPath +  "froggerDead.png";
	Textures[22].src = "../img/" + colorPath +  "log3.png";
	Textures[23].src = "../img/" + colorPath +  "log4.png";
	Textures[24].src = "../img/" + colorPath +  "Fly.png";
	Textures[25].src = "../img/Explosion1.png";
	Textures[26].src = "../img/Explosion2.png";
}

function showMenu(fadeIn){
	
	var divMenu = document.getElementById('overlay');
  
  	setDivPosition(divMenu);

	$("#p_colorScheme").css("visibility", "visible");
	$('#p_newGame').css("visibility", "visible");
	$("#p_highscore").css("visibility", "visible");

	if(fadeIn == true)
	{
		$('#overlay').fadeIn(1000);
	}
	else
	{
		$('#overlay').css("display", "inline");
	}
}

function hideMenu(){
   $('#overlay').fadeOut(500, function (){
        	EnableControls = true;
        });
}

function setDivPosition(div){
	
	// Set the div position of the overlay according to the canvas position
	var canvas = document.getElementById('theCanvas');
	
	div.style.width = canvas.width + 10 + 'px';
   	div.style.height =  canvas.height + 10 + 'px';
   	div.style.top = canvas.style.top;
	div.style.left = canvas.style.left;
	div.style.marginLeft = canvas.style.marginLeft;
	div.style.marginTop = canvas.style.marginTop;
}

function startCountdown(){
	// Show countdown
	$('#p_countdown').css("visibility", "visible");
	$('#p_countdown').css("font-size", "8pt");
	$('#p_countdown').css("margin-top", "20%");
    $("#p_countdown").html("3");
    
	$("#p_countdown").animate({
		"fontSize":"120pt"}, 1000, function(){
			
		$('#p_countdown').css("font-size", "8pt");
		$('#p_countdown').css("margin-top", "20%");
	    $("#p_countdown").html("2");
    
		$("#p_countdown").animate({
			"fontSize":"120pt"}, 1000, function(){
				
			$('#p_countdown').css("font-size", "8pt");
			$('#p_countdown').css("margin-top", "20%");
		    $("#p_countdown").html("1");
    
			$("#p_countdown").animate({
				"fontSize":"120pt"}, 1000, function(){
			
					hideMenu();
					$('#p_countdown').css("visibility", "hidden");
					StartTime = new Date().getTime();
					EnableControls = true;  	
				});
				});
		});
	
}

function setTitleAndIcon(theGameMode)
{
	$("#favicon").remove(); 
	if(theGameMode == GameMode.USK12)
	{
		$('<link id="favicon" type="image/x-icon" rel="shortcut icon" href="../img/clr/frogger.png" />').appendTo('head');
		document.title = "Frogger";
		$("#theCanvas").css("border-color", "green");
	}
	else if(theGameMode == GameMode.USK18)
	{
		$('<link id="favicon" type="image/x-icon" rel="shortcut icon" href="../img/froggerDead.png" />').appendTo('head');
		document.title = "Frogger:The massacre";
		$("#theCanvas").css("border-color", "white");
	}
}

function showWin(){
	// Show the time and a special textfield
	Runtime = (EndTime - StartTime) / 1000;
	Runtime = Runtime.toFixed(2);
	var expirationDate = getExpirationDate();	
	document.cookie += 'zeit=' + Runtime + ',;expires=' + expirationDate.toGMTString( ) + '; path=/;'; 
	$("#p_win").html("YOU WIN! <br><font size=-1>" + Runtime + "s</font>");
	$('#p_win').css("visibility", "visible");
}

function getExpirationDate(){
	
var expireDays = 365;

// Expire time in ms
var expireTime = expireDays * 1000 * 60 * 60 * 24;

var expires_date = new Date(new Date().getTime() + expireTime);

return expires_date;
}

function bubbleSort(arrayTimes){
	
   var i;
   var iJ;
   var iTemp;

   for (i = arrayTimes.length; i > 1; i--)
   {
      for (iJ = 0; iJ < arrayTimes.length - 1; iJ++)
      {
         //Check if current position is greater then the following position
         if (arrayTimes[iJ] > arrayTimes[iJ + 1])
         {
            //Swap the two array positions
            iTemp = arrayTimes[iJ + 1];
            arrayTimes[iJ + 1] = arrayTimes[iJ];
            arrayTimes[iJ] = iTemp;
         }
      }
   }
   
   return arrayTimes;
}

function createHighscoreList(times){
	
	var sortedList = document.getElementById("highscore_list");
	
	// Remove all childs first
	if ( sortedList.hasChildNodes() )
	{
	    while (sortedList.childNodes.length >= 1 )
	    {
	        sortedList.removeChild(sortedList.firstChild );       
	    } 
	}
	
	for (var i = 0; i < 10; i++){
		
		var li = document.createElement("li");
		if(times[i] != undefined)
		{
			var p = document.createTextNode(times[i] + "s");
		}
		else
		{
			var p = document.createTextNode("--:--");
		}
		li.appendChild(p);
		sortedList.appendChild(li);
		// Only display the 10 best highscore times
	}

}


$(document).ready(function() {
	
	// Initialize all global values
	initGlobal();

	$("#p_newGame").click(function () {
		// "New Game" was clicked disable all text fields
  		$('#p_win').css("visibility", "hidden");
    	$('#p_newGame').css("visibility", "hidden");
    	$("#p_colorScheme").css("visibility", "hidden");
    	$("#p_highscore").css("visibility", "hidden");
		CurrentGameMode = newGameMode;
		// Reload textures (maybe the user changed the "GameMode")
		loadTextures();
		// 
    	c_handler.initialize();
    	// Controls will be enabled after the countdown finished
  		EnableControls = false;  	
		startCountdown();
		setTitleAndIcon(CurrentGameMode);
    });
    
    $("#p_colorScheme").click(function () {
		
		// Change the "GameMode"
		switch(newGameMode)
		{
			case GameMode.USK18:
				$("#p_colorScheme").html("COLOR SCHEME: USK12");
				newGameMode = GameMode.USK12;
			break;
			case GameMode.USK12:
				$("#p_colorScheme").html("COLOR SCHEME: USK18");
				newGameMode = GameMode.USK18;
			break;
		}
    });
    
    $("#p_highscore").click(function () {
    	// Array to save all times stored in cookie
    	var times = new Array();
    	// Get current cookie
    	var cookie = document.cookie;
    	
    	// Check if cookie exists
		if(document.cookie){
			// Iterate through cookie and get all times
			while(cookie != ''){
				cookieValue = cookie.substr(cookie.search('=')+1, cookie.search(',') - (cookie.search('=') + 1));
				cookie = cookie.substr(cookie.search(',') + 1);
				times.push(cookieValue);
				} 
		}
		// Sort the times
		times = bubbleSort(times);
		createHighscoreList(times);

		var divHighscore = document.getElementById('highscore');
		// Set the center position for highscore div
  		setDivPosition(divHighscore);
  		// Hide menu div
		$('#overlay').hide();		
		// Show highscore div
		$('#highscore').fadeIn(500);
    });
    
   	$("#p_back").click(function () {
   		
   		// Go back to main menu
		$('#highscore').hide();
		$('#overlay').fadeIn(500);
    });

	// Change cursor to pointer and highlight p for the following elements
    
    $('#p_newGame').hover(
	  function () {
	   	$(this).css('cursor','pointer');
	   	$("#p_newGame").css('color','lightgrey');
	  }, 
	  function () {
	  	$("#p_newGame").css('color','white');
	  }
	);
	
   $('#p_colorScheme').hover(
	  function () {
	   	$(this).css('cursor','pointer');
	   	$("#p_colorScheme").css('color','lightgrey');
	  }, 
	  function () {
	  	$("#p_colorScheme").css('color','white');
	  }
	);
	
	$('#p_highscore').hover(
	  function () {
	   	$(this).css('cursor','pointer');
	   	$("#p_highscore").css('color','lightgrey');
	  }, 
	  function () {
	  	$("#p_highscore").css('color','white');
	  }
	);

	$('#p_back').hover(
	  function () {
	   	$(this).css('cursor','pointer');
	   	$("#p_back").css('color','lightgrey');
	  }, 
	  function () {
	  	$("#p_back").css('color','white');
	  }
	);

});